/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */
class ListNode {
    val: number
    next: ListNode | null
    constructor(val?: number, next?: ListNode | null) {
        this.val = (val === undefined ? 0 : val)
        this.next = (next === undefined ? null : next)
    }
}

function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
    if (!headA || !headB) return null;

    let pointerA: ListNode | null = headA;
    let pointerB: ListNode | null = headB;

    // 当两个指针不相等时继续遍历
    while (pointerA !== pointerB) {
        // 如果 pointerA 到达末尾，转到 headB
        pointerA = pointerA ? pointerA.next : headB;
        // 如果 pointerB 到达末尾，转到 headA
        pointerB = pointerB ? pointerB.next : headA;
    }

    // 返回相交节点（如果不相交，两个指针会同时为 null）
    return pointerA;
}